from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QDesktopWidget, QGraphicsBlurEffect
from PyQt5.QtCore import QPropertyAnimation, QRect, QEasingCurve, Qt, QTimer 
from PyQt5.QtGui import QPixmap ,QPainter,QPen,QColor
import psutil
import sys

app = QApplication(sys.argv)

desktop = QDesktopWidget()
screen_rect = desktop.screenGeometry()
width = screen_rect.width()
height = screen_rect.height()

# 主窗口防止立即退出（必要时隐藏）
main_window = QWidget()
main_window.hide()

class CircleProgress(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.bg_color = Qt.gray
        self.pg_color = QColor("#4beb73")
        self.percent = 0.0
        self.current_angle = 0  # 当前绘制角度（0~360）
        self.animation_duration = 200  # 动画总时长（毫秒）
        self.animation_timer = QTimer(self)  # 定时器控制动画帧
        self.is_animating = False  # 动画状态标记

    def set_percent(self, percent):
        if self.is_animating:  # 避免重复触发
            return

        target_angle = int(360 * percent)  # 目标角度
        self.animation_timer.stop()  # 停止之前的动画
        
        try:
            self.animation_timer.timeout.disconnect()  # 清除之前的连接
        except TypeError:
            pass  # 如果没有连接任何槽函数，则忽略错误

        self.animation_timer.timeout.connect(
            lambda: self.update_angle(target_angle)
        )
        self.animation_timer.start(10)  # 每 10ms 更新一次
        self.is_animating = True
        self.percent = percent

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        
        # 背景圆环（固定绘制）
        bg_pen = QPen(self.bg_color, 30)
        painter.setPen(bg_pen)
        rect = self.rect().adjusted(15, 15, -15, -15)
        painter.drawEllipse(rect)
        
        # 动态进度圆环
        pg_pen = QPen(self.pg_color, 30)
        painter.setPen(pg_pen)
        start_angle = -90 * 16  # 起始角度（Qt单位：1/16度）
        span_angle = int(self.current_angle * 16)  # 动态绘制角度
        painter.drawArc(rect, start_angle, span_angle)
    def update_angle(self, target_angle):
        if self.is_animating and self.current_angle < target_angle:
            step = 360 / (self.animation_duration / 8)  # 每帧增加的角度
            self.current_angle += step
            if self.current_angle > target_angle:
                self.current_angle = target_angle
            self.update()
        elif self.current_angle >= target_angle:
            self.current_angle = target_angle
            self.animation_timer.stop()
            self.is_animating = False
            self.update()

# 充电提示窗口（全屏模糊背景）
charge_window = QWidget()
charge_window.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
charge_window.setAttribute(Qt.WA_TranslucentBackground)
charge_window.setGeometry(0, 0, width, height)
charge_window.setWindowOpacity(0)

def show_charge_window_fade_in():
    global fade_animation
    charge_window.show()
    charge_window.setWindowOpacity(0)
    fade_animation = QPropertyAnimation(charge_window, b"windowOpacity")
    fade_animation.setDuration(500)  # 动画持续时间：500ms
    fade_animation.setStartValue(0)
    fade_animation.setEndValue(1)
    fade_animation.setEasingCurve(QEasingCurve.InOutQuad)
    charged_text.raise_()
    circle_progress.raise_()
    charged_icon.raise_()
    fade_animation.start()
def hide_charge_window_fade_out():
    global fade_animation
    fade_animation = QPropertyAnimation(charge_window, b"windowOpacity")
    fade_animation.setDuration(500)
    fade_animation.setStartValue(1)
    fade_animation.setEndValue(0)
    fade_animation.finished.connect(charge_window.hide)
    fade_animation.start()

#充电图标
charged_icon = QLabel(charge_window)
icon_pixmap = QPixmap("./pic/charged.PNG")
charged_icon.setPixmap(icon_pixmap.scaled(90,180))  # 根据需要调整大小
charged_icon.move(width // 2 - 45,height // 2 - 90)  # 屏幕中心

# 充电提示文本
charged_text = QLabel(charge_window)
charged_text.setStyleSheet("""
    QLabel {
        font-family: '微软雅黑';
        font-size: 50px;
        height: 40px;
        font-weight: bold;
        color: white; 
        background-color: transparent;
    }
""")
charged_text.setGeometry(width // 2- 145 ,height // 2 - 228 + 456 + 200 ,350, 150)

#圆环组件
circle_progress = CircleProgress(charge_window)
circle_progress.resize(600, 600)  # 直径240px（根据图标尺寸调整）
circle_progress.setGeometry(width // 2 - 300,height // 2 - 228 - 60 , 600, 600)
circle_progress.setStyleSheet("background-color: transparent;")





# 截图并模糊背景
background_label = None
def blur_background():
    global background_label
    if background_label:
        background_label.deleteLater()
    screen = QApplication.primaryScreen()
    screenshot = screen.grabWindow(QApplication.desktop().winId())
    background_label = QLabel(charge_window)
    background_label.setPixmap(screenshot.scaled(width, height))
    background_label.resize(width, height)
    blur_effect = QGraphicsBlurEffect()
    blur_effect.setBlurRadius(20)
    background_label.setGraphicsEffect(blur_effect)



# 无电池提示窗口
no_battery_anime_window = QWidget()
no_battery_anime_window.setWindowFlags(no_battery_anime_window.windowFlags() | Qt.FramelessWindowHint)
no_battery_anime_window.setAttribute(Qt.WA_TranslucentBackground)
no_battery_anime_window.resize(300, 250)

no_battery = QLabel(no_battery_anime_window)
no_battery.setStyleSheet("""
    QLabel {
        font-family: '微软雅黑';
        font-size: 16px;
        background-color: #E6E6E6;
        border-radius: 20px;
        padding-left: 100px;
        height: 40px;
    }
""")
no_battery.setText("你电池呢？妹找到啊！")
no_battery.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
no_battery.setGeometry(0, 130, 300, 40)

no_battery_icon = QLabel(no_battery_anime_window)
pixmap = QPixmap("./pic/huh.PNG")
no_battery_icon.setPixmap(pixmap.scaled(40, 40))
no_battery_icon.setGeometry(30, 130, 40, 40)

# 动画部分
no_battery_animation = QPropertyAnimation(no_battery_anime_window, b"geometry")
no_battery_animation.setDuration(500)
no_battery_animation.setStartValue(QRect(width // 2 - 150, -300, 300, 250))
no_battery_animation.setEndValue(QRect(width // 2 - 150, -120, 300, 250))
no_battery_animation.setEasingCurve(QEasingCurve.InOutQuad)

def exit_after_animation():
    exit_animation = QPropertyAnimation(no_battery_anime_window, b"geometry")
    exit_animation.setDuration(500)
    current_geo = no_battery_anime_window.geometry()
    exit_animation.setStartValue(current_geo)
    exit_animation.setEndValue(QRect(current_geo.x(), -current_geo.height(), current_geo.width(), current_geo.height()))
    exit_animation.setEasingCurve(QEasingCurve.OutQuad)
    exit_animation.finished.connect(app.quit)
    exit_animation.start()




# 监听电池状态函数
last_power_plugged = None

def check_battery_status():
    global last_power_plugged
    battery = psutil.sensors_battery()
    if battery is not None:
        current_power_plugged = battery.power_plugged
        # 检测插电事件
        if current_power_plugged and last_power_plugged is False:
            blur_background()
            show_charge_window_fade_in()
            charged_text.setText(f"电量:{battery.percent}%")
            
            # 重置圆环状态并重新绘制
            circle_progress.current_angle = 0  # 重置角度
            circle_progress.is_animating = False  # 确保动画可以重新触发
            circle_progress.set_percent(battery.percent / 100)
            
            QTimer.singleShot(3000, hide_charge_window_fade_out)

        last_power_plugged = current_power_plugged  # 更新状态


battery_timer = QTimer()
battery_timer.timeout.connect(check_battery_status)
battery_timer.start(1000)



# 初始检查一次
battery = psutil.sensors_battery()
if battery is not None:
    last_power_plugged = battery.power_plugged  # 初始化 last_power_plugged
else:
    last_power_plugged = False

if battery is None:
    no_battery_animation.start()
    QTimer.singleShot(2000, exit_after_animation)
elif battery.power_plugged:
    blur_background()
    show_charge_window_fade_in()
    charged_text.setText(f"电量:{battery.percent}%")
    circle_progress.set_percent(battery.percent / 100)
    QTimer.singleShot(3000, hide_charge_window_fade_out)  # 显示后3秒隐藏

# 启动主事件循环
sys.exit(app.exec_())